package com.stupidzhe.jdklearning.io.zip;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Mr.W on 2017/11/12.
 */
public class ZIPTestClass {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.exit(-1);
            return;
        }
        final String zipName = args[0];
        try {
            File directFile = new File(zipName);
            if (directFile.exists()) {
                zip(directFile, directFile.getParent() + "/" + directFile.getName() + ".zip");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void zip(File directFile, String sourceFileName) throws IOException {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(sourceFileName));

        zip(out, directFile, directFile.getName());
        out.close();
    }

    private static void zip(ZipOutputStream out, File sourceFile, String base) throws IOException {
        if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            if (null != files && files.length > 0) {
                out.putNextEntry(new ZipEntry(base + "/"));
                for (File cFile : files) {
                    if (cFile.getName().equals(".DS_Store")) {
                        continue;
                    }
                    zip(out, cFile, base + "/" + cFile.getName());
                }
            }
        } else if (sourceFile.isFile()) {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            int content;
            while (-1 != (content = fileInputStream.read())) {
                out.write(content);
            }
            fileInputStream.close();
        }
    }
}
